package pers.zdb.ag.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import pers.zdb.ag.pojo.GaodeAddress;
import pers.zdb.ag.util.HttpUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 获取高德的
 * @author: Adobe Chow
 * @date: 2018/8/8 14:35
 * @Copyright: www.winshang.com Inc. All rights reserved.
 */
public class GaodeDataDownload {
    /**高德api key */
    private final static String key = "0607899bebd24c4d9ddae885064b3cf7";
    /**获取全国的省市区 */
    private  final  static String chinaUrl = "https://restapi.amap.com/v3/config/district?key="+key+"&keywords=中国&subdistrict=3&extensions=base";
    /**获取地区边际  */
    private final  static String polylineUrl = "https://restapi.amap.com/v3/config/district?key="+key+"&subdistrict=0&extensions=all&keywords=";

    private final  static String STATUS_OK = "1";

    public static void main(String[] args) {
        //运行次方法将数据文件下载到本地，然后替换资源文件里面
        saveEveryAddressDataToDisk("d:\\gaode\\");
    }

    /**
     * 将数据分批保存到本地
     */
    public static void saveEveryAddressDataToDisk(String path){
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdir();
        }

        List<GaodeAddress> list =getGaodeAddressList();
        System.out.println("总共:"+list.size()+"个地区");

        for (GaodeAddress gaodeAddress:list) {
            String url = polylineUrl + gaodeAddress.getAdcode();
            String resultStr = HttpUtils.getAndTry(url);
            JSONObject result = JSONObject.parseObject(resultStr);
            System.out.println(gaodeAddress.getName()+"边界值：:"+result);
            if (result!=null&&STATUS_OK.equals(result.getString("status"))&&result.getIntValue("count")>0){
                JSONArray districts = result.getJSONArray("districts");
                JSONObject district = districts.getJSONObject(0);
                String polyline = district.getString("polyline");

                //     分批保存
                GaodeAddress gaodeAddressNew =new GaodeAddress();
                gaodeAddressNew.setPolyline(polyline);
                gaodeAddressNew.setParentAdcode(gaodeAddress.getParentAdcode());
                gaodeAddressNew.setLevelCode(gaodeAddress.getLevelCode());
                gaodeAddressNew.setLevel(gaodeAddress.getLevel());
                gaodeAddressNew.setName(gaodeAddress.getName());
                gaodeAddressNew.setAdcode(gaodeAddress.getAdcode());
                File file = new File(path+gaodeAddressNew.getAdcode()+".json");

                try {
                    PrintWriter printWriter = new PrintWriter(file);
                    printWriter.write(JSON.toJSONString(gaodeAddressNew));
                    printWriter.close();
                    System.out.println(gaodeAddressNew.getName()+"保存至"+file.getAbsolutePath()+"成功");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println("所有保存完毕:"+list.size());
    }





    /**
     * 从高德官网获取省市区列表
     * @return
     */
    private static List<GaodeAddress> getGaodeAddressList(){
        List<GaodeAddress> list = new ArrayList<>();

        String provinceCityAreaStr = HttpKit.get(chinaUrl);
        JSONObject provinceCityArea = JSONObject.parseObject(provinceCityAreaStr);
        System.out.println("获取全国的省市区:"+provinceCityAreaStr);
        if (provinceCityArea!=null&&STATUS_OK.equals(provinceCityArea.getString("status"))){
            //全国省市区
            JSONObject country = provinceCityArea.getJSONArray("districts").getJSONObject(0);

            //国家
            list.add(getGaodeAddress(country,null));

            JSONArray provinceList = country.getJSONArray("districts");
            for (int i=0;i<provinceList.size();i++) {
                //省份
                JSONObject province = provinceList.getJSONObject(i);
                list.add(getGaodeAddress(province,country));

                JSONArray cityList = province.getJSONArray("districts");
                for (int j=0;j<cityList.size();j++) {
                    //城市
                    JSONObject city = cityList.getJSONObject(j);
                    list.add(getGaodeAddress(city,province));

                    JSONArray areaList = city.getJSONArray("districts");
                    for (int k=0;k<areaList.size();k++) {
                        //市辖区
                        JSONObject area = areaList.getJSONObject(k);
                        list.add(getGaodeAddress(area,city));
                    }

                }

            }

        }

        return list;
    }




    /**
     *
     * @param district
     * @param parentDistrict 父节点
     * @return
     */
    private static GaodeAddress getGaodeAddress(JSONObject district,JSONObject parentDistrict){
        GaodeAddress gaodeAddress = new GaodeAddress();
        gaodeAddress.setAdcode(district.getString("adcode"));
        gaodeAddress.setName(district.getString("name"));
        gaodeAddress.setLevel(district.getString("level"));
        if (parentDistrict!=null){
            gaodeAddress.setParentAdcode(parentDistrict.getString("adcode"));
        }

        if ("country".equals(district.getString("level"))){
            gaodeAddress.setLevelCode(0);
        }else if ("province".equals(district.getString("level"))){
            gaodeAddress.setLevelCode(1);
        }else if ("city".equals(district.getString("level"))){
            gaodeAddress.setLevelCode(2);
        }else if ("district".equals(district.getString("level"))){
            gaodeAddress.setLevelCode(3);
        }
        return gaodeAddress;
    }

}
